package io.renren.modules.sys.controller;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.modules.app.PicSuffix;
import io.renren.modules.app.entity.AgentEntity;
import io.renren.modules.app.entity.OrderEntity;
import io.renren.modules.app.entity.UserCarEntity;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.OrderPOJO;
import io.renren.modules.app.service.*;
import io.renren.modules.sys.entity.SysUserRoleEntity;
import io.renren.modules.sys.service.SysUserRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Auther zxl
 * @Date 2018/12/17 18:25
 * @Description
 **/
@RestController
@RequestMapping("/sys/check-car")
public class SysCheckCarController extends AbstractController {

    @Autowired
    private AgentService agentService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserCarService userCarService;
    @Autowired
    private OrderService orderService;
    @Autowired
    AlipayNotifyService alipayNotifyService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 图片路径
     */
    @Value("${check-car.drivePicPath}")
    String drivePicPath;

    private final ResourceLoader resourceLoader;

    @Autowired
    public SysCheckCarController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    /**
     * 查询所有订单
     * @param params
     * @return
     */
    @GetMapping("/order/list")
    public R getAllOrders(@RequestParam Map<String, Object> params){


        SysUserRoleEntity userRoleEntity = sysUserRoleService.queryByUserId(getUserId());
        // 代理商账号只能看到自己的订单
        if (userRoleEntity.getRoleId() == 2){
            params.put("agentId",userRoleEntity.getAgentId().toString());
        }

        PageUtils page = orderService.queryPage(params);

        return R.ok().put("page",page);
    }


    /**
     * 列表
     * @param params
     * @return
     */
    @GetMapping("/agent/list")
    public R list(@RequestParam Map<String, Object> params) {

        PageUtils page = agentService.queryPage(params);

        return R.ok().put("page",page);

    }

    /**
     * 保存
     * @param agentEntity
     * @return
     */
    @PostMapping("/agent/save")
    public R save(@RequestBody AgentEntity agentEntity){

        ValidatorUtils.validateEntity(agentEntity, AddGroup.class);

        agentService.addOneAgent(agentEntity);

        return R.ok("添加成功");
    }

    /**
     * 更新
     * @param agentEntity
     * @return
     */
    @PostMapping("/agent/update")
    public R update(@RequestBody AgentEntity agentEntity){

        ValidatorUtils.validateEntity(agentEntity, AddGroup.class);
        agentService.update(agentEntity);

        return R.ok("更新成功");
    }

    /**
     * 查询
     * @param agentId
     * @return
     */
    @GetMapping("/agent/get/{agentId}")
    public R selectByName(@PathVariable String agentId){

        AgentEntity agentEntity = agentService.queryById(Integer.parseInt(agentId));

        return R.ok().put("agent",agentEntity);

    }

    /**
     * 列表
     * @param params
     * @return
     */
    @GetMapping("/user/list")
    public R userList(@RequestParam Map<String, Object> params) {

        PageUtils page = userService.queryPage(params);

        return R.ok().put("page",page);
    }

    /**
     * 查行驶证信息
     * @return
     */
    @GetMapping("/userCar/getCarInfo/{userId}")
    public R carInfo(@PathVariable("userId") Integer userId){

        System.out.println("into");
        long userId_l = userId;
        UserCarEntity userCarEntity = userCarService.queryOneByUserId(userId_l);

        return R.ok().put("carInfo",userCarEntity);
    }

    /**
     * 获取行驶证照片
     * @param request
     * @return
     */
    @GetMapping (value = "/showCarPic/{userId}",produces = MediaType.IMAGE_JPEG_VALUE)
    public ResponseEntity<?> showHP(HttpServletRequest request,
                                    @PathVariable(value = "userId",required = true) String userId) {

        String image_name = userId+ PicSuffix.DRIVING_LICENSE_PIC.getSuffix();
        try {
            return ResponseEntity.ok(resourceLoader.
                    getResource("file:" +drivePicPath+"/"+userId+PicSuffix.DRIVING_LICENSE_PIC.getSuffix() ));
        }catch (Exception e){
            return ResponseEntity.notFound().build();
        }

    }

    /**
     * 查询用户订单
     * @param request
     * @return
     */
    @GetMapping("/userOrders/{orderId}")
    public R userOrders(HttpServletRequest request,@PathVariable(value = "orderId",required = true) String orderId){



        if (StringUtils.isBlank(orderId)){
            return R.error("orderId不能为空");
        }

        OrderPOJO orderPOJO = new OrderPOJO();
        OrderEntity orderEntity = orderService.getOneByOrderId(orderId);
        if (orderEntity != null){

            SysUserRoleEntity userRoleEntity = sysUserRoleService.queryByUserId(getUserId());
            // 代理商账号只能看到自己的订单
            if (userRoleEntity.getRoleId() == 2 && orderEntity.getAgentId() != userRoleEntity.getAgentId()){
                return R.error("不能看到别人的订单");

            }

            orderPOJO.setOrderEntity(orderEntity);
            orderPOJO.setUserEntity(userService.queryByUserId(orderEntity.getUserId()));
            orderPOJO.setUserCarEntity(userCarService.queryOneByUserId(orderEntity.getUserId()));
            orderPOJO.setAgentEntity(agentService.queryById(orderEntity.getAgentId()));
            orderPOJO.setAlipayNotifyEntity(alipayNotifyService.getOne(orderEntity.getOrderId()));
            return R.ok().put("data",orderPOJO);
        }
        return R.error("订单不存在");
    }

    /**
     * 接单
     * @return
     */
    @GetMapping("/doOrder/{orderId}")
    public R doOrder(@PathVariable(value = "orderId",required = true) String orderId){

        if (StringUtils.isBlank(orderId)){
            return R.error("订单id不能为空");
        }
        boolean b = orderService.updateOrderState(orderId,3);
        if (b){
            return R.ok("处理成功");
        }
        return R.error("处理失败");
    }

    /**
     * 拒单
     * @param orderId
     * @param reason
     * @return
     */
    @GetMapping("/rejectOrder")
    public R rejectOrder(@RequestParam(value = "orderId",required = true) String orderId,
                         @RequestParam(value = "reason",required = true) String reason){

        if (StringUtils.isBlank(orderId)){
            return R.error("订单id不能为空");
        }
        OrderEntity orderEntity = orderService.getOneByOrderId(orderId);
        if (orderEntity.getOrderState() == 7){
            return R.error("订单已拒绝！");
        }else if (orderEntity.getOrderState() > 3 && orderEntity.getOrderState() == 10){
            return R.error("订单已经开始，不能拒绝！");
        }
        boolean b = orderService.rejectOrder(orderId,reason);
        if (b){
            return R.ok("处理成功");
        }
        return R.error("处理失败");
    }

    /**
     * 查询用户姓名
     * @param userId
     * @return
     */
    @GetMapping("/username")
    public R username(@RequestParam(value = "userId",required = true) String userId){

        UserEntity userEntity = userService.queryByUserId(Long.parseLong(userId));
        if (userEntity!=null){
            return R.ok().put("username",userEntity.getUsername());
        }
        return R.error("未查到");

    }


}
